package smartt.styy.auth.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import smartt.styy.auth.biz.TypeRelationBiz;
import smartt.styy.auth.biz.UserBiz;
import smartt.styy.auth.constants.ServerConstants;
import smartt.styy.auth.model.entity.TbAuUser;
import smartt.styy.auth.model.entity.TbTypeRelation;
import smartt.styy.auth.model.request.UserInfoReq;
import smartt.styy.auth.model.response.UserBaseInfoRsp;
import smartt.styy.auth.util.DESEncrypt;
import smartt.styy.auth.util.MD5Util;
import smartt.styy.auth.util.PwdUtils;
import smartt.styy.common.constant.RestCodeConstants;
import smartt.styy.common.constant.UserConstant;
import smartt.styy.common.exception.BaseException;
import smartt.styy.common.msg.ObjectRestResponse;

@RestController
@RequestMapping("user")
@Slf4j
@Api(value="UserController",tags="[用户登录后-相关操作]")
public class UserController {

	@Autowired
	private UserBiz userBiz;
	
	@Autowired
	private TypeRelationBiz typeRelationBiz;
	
	@Value("${3des.key}")
	private String desKey;
	
	/**
	 * Description:获取用户基本信息 <br>
	 * @author stf<br>
	 * @param UserInfoReq <br>
	 * @return String <br>
	 * @throws Exception 
	 * @throws BaseException <br>
	 * */
	@SuppressWarnings("unchecked")
	@GetMapping("/{id}")
	@ApiOperation(value="[用户相关操作]-[根据id获取用户基本信息]", notes="根据id获取用户基本信息")
	@ApiImplicitParam(name = "userId", value = "用户Id（密文）", required = true, dataType = "String", paramType="query")
	public ObjectRestResponse<Object> getUserInfo(String userId) throws Exception{
		log.info("[用户相关操作]-[根据id获取用户基本信息] start ...");
		
		UserBaseInfoRsp userBaseInfo = new UserBaseInfoRsp();
		ObjectRestResponse<Object> objectRestResp = new ObjectRestResponse<Object>();
		try {
			Integer uesrId= Integer.parseInt(DESEncrypt.decryptMode(desKey,userId));
			TbAuUser tbUser = userBiz.selectById(uesrId);
			if(tbUser == null){
				objectRestResp.setStatus(UserConstant.USER_NOT_EXIST_CODE);
				objectRestResp.setMessage(UserConstant.USER_NOT_EXIST_MSG);
				objectRestResp.setRel(false);
				return objectRestResp;
				
			}
			BeanUtils.copyProperties(tbUser, userBaseInfo);
			if(tbUser.getParentId() != ServerConstants.USER_Id_ZERO && tbUser.getParentId() !=null){
				userBaseInfo.setParentId(DESEncrypt.encryptMode(desKey, tbUser.getParentId().toString()));
			}else{
				userBaseInfo.setParentId(ServerConstants.USER_Id_ZERO.toString());
			}
			
			userBaseInfo.setUserId(userId);
			Map<String,Object> reqMap =new HashMap<String,Object>();
			reqMap.put("userId", uesrId);
			List<TbTypeRelation> lst = typeRelationBiz.selectByQuery(reqMap);
			String userTypes = new String();
			StringBuffer sb = new StringBuffer();
			for (TbTypeRelation tbTypeRelation : lst) {
				sb.append(tbTypeRelation.getUsertypeId());
				sb.append(",");
			}
			userTypes = sb.toString().substring(0,sb.toString().length() - 1);
			userBaseInfo.setUserTypes(userTypes);
		} catch (Exception e) {
			log.error("[用户相关操作]-[根据id获取用户基本信息]，异常message:"+e.getMessage(),RestCodeConstants.THROW_ERROR_CODE);
			throw new BaseException("[用户相关操作]-[根据id获取用户基本信息]，异常message:"+e.getMessage(),RestCodeConstants.THROW_ERROR_CODE);
		}
		return objectRestResp.data(userBaseInfo).rel(true);
	}
	
	/**
	 * Description:更新用户基本信息 <br>
	 * @author stf<br>
	 * @param UserInfoReq <br>
	 * @return String <br>
	 * @throws BaseException <br>
	 * */
	@SuppressWarnings("unchecked")
	@PutMapping("/updateUserInfo")
	@ApiOperation(value="[用户相关操作]-[更新用户基本信息]", notes="更新用户基本信息")
	@ApiImplicitParam(name = "param", value = "更新用户基本信息param", required = true, dataType = "UserInfoReq")
	public ObjectRestResponse<Object> updateUserInfo(@RequestBody UserInfoReq param){
		log.info("[用户相关操作]-[更新用户基本信息] start ...");
		ObjectRestResponse<Object> objectRestResp = new ObjectRestResponse<Object>();
		try {
			TbAuUser auUser = new TbAuUser();
			
			//校验手机号码是否已被注册
			if(!StringUtils.isEmpty(param.getTelPhone())){
				Map<String,Object> reqMap =new HashMap<String,Object>();
				reqMap.put("status", ServerConstants.USER_STATUS_1);
				reqMap.put("telPhone", param.getTelPhone());
				TbAuUser tbUser = userBiz.selectUserInfoByParams(reqMap);
				if(tbUser != null){
					log.warn("[用户相关操作]-[更新用户基本信息]--电话号码已存在！");
					objectRestResp.setStatus(UserConstant.USER_PHONE_CODE);
					objectRestResp.setMessage(UserConstant.USER_PHONE_MSG);
					objectRestResp.setRel(false);
					return objectRestResp;
				}
			}
			
			String userId = param.getUserId();
			BeanUtils.copyProperties(param, auUser);
			auUser.setId(Integer.parseInt(DESEncrypt.decryptMode(desKey,userId)));
			auUser.setUpdateAt(new Date());
			userBiz.updateSelectiveById(auUser);
		} catch (Exception e) {
			log.error("[用户相关操作]-[更新用户基本信息]-异常，错误message:"+e.getMessage());
			throw new BaseException("[用户相关操作]-[更新用户基本信息]-异常，错误message:"+
					e.getMessage(),RestCodeConstants.THROW_ERROR_CODE);
		}
		log.info("[用户相关操作]-[更新用户基本信息] end 。");
		return objectRestResp.rel(true);
		
	}
	
	/**
	 * Description:修改密码 <br>
	 * @author stf<br>
	 * @param UserInfoReq <br>
	 * @return String <br>
	 * @throws BaseException <br>
	 * */
	@SuppressWarnings("unchecked")
	@PutMapping("/updatePwd")
	@ApiOperation(value="[用户相关操作]-[修改密码操作]", notes="修改密码操作")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户Id（密文）", required = true, dataType = "String", paramType="query"),
		@ApiImplicitParam(name = "newPassWord", value = "用户新密码", required = true, dataType = "String", paramType="query")
	})
	public ObjectRestResponse<Object> updatePwd(String userId,String newPassWord){
		log.info("[用户相关操作]-[修改密码操作]-start ...");
		ObjectRestResponse<Object> objectRestResp = new ObjectRestResponse<Object>();
		try {
			TbAuUser updateUser =new TbAuUser();
			Integer UserId = Integer.parseInt(DESEncrypt.decryptMode(desKey,userId));
			TbAuUser auUser = userBiz.selectById(UserId);
			if(null == auUser){
				log.warn("[用户相关操作]-[修改密码操作]--未查询到用户信息！");
				objectRestResp.setStatus(UserConstant.USER_NOT_EXIST_CODE);
				objectRestResp.setMessage(UserConstant.USER_NOT_EXIST_MSG);
				objectRestResp.setRel(false);
				return objectRestResp;
			}
			updateUser.setId(UserId);
			String dbPassword = PwdUtils.generateDbPwd(auUser.getUsername(),newPassWord);
			updateUser.setPassword(MD5Util.encrypt(dbPassword));
			updateUser.setUpdateAt(new Date());
			userBiz.updateSelectiveById(updateUser);
		} catch (Exception e) {
			log.error("[用户相关操作]-[修改密码操作]-异常，错误message:"+e.getMessage());
			throw new BaseException("[用户相关操作]-[修改密码操作]-异常，错误message:"+
									e.getMessage(),RestCodeConstants.THROW_ERROR_CODE);
		}
		log.info("[用户相关操作]-[修改密码操作] end 。");
		return objectRestResp.rel(true);
	}
	
	/**
	 * Description:添加角色类型 <br>
	 * @author stf<br>
	 * @param UserInfoReq <br>
	 * @return String <br>
	 * @throws Exception 
	 * @throws NumberFormatException 
	 * @throws BaseException <br>
	 * */
	@SuppressWarnings("unchecked")
	@PutMapping("/addUserTypeRelation")
	@ApiOperation(value="[用户相关操作]-[添加角色类型]", notes="添加角色类型")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户Id（密文）", required = true, 
							dataType = "String", paramType="query"),
		@ApiImplicitParam(name = "userTypes", value = "用户类型','分割 --说明：（1:游客，2：导游，3：旅行社，4,：游企）", 
							required = true, dataType = "String", paramType="query")
	})
	public ObjectRestResponse<Object> addUserTypeRelation(String userId,String userTypes) throws Exception{
		log.info("[用户相关操作]-[添加角色类型] start ...");
		Integer userBeanId = Integer.parseInt(DESEncrypt.decryptMode(desKey,userId));
		ObjectRestResponse<Object> objectRestResp = new ObjectRestResponse<Object>();
		try {
			String [] userTypesArr = userTypes.split(",");
			if(userTypesArr.length>0){
				for (String userTps : userTypesArr) {
					TbTypeRelation tb_relation =new TbTypeRelation();
					tb_relation.setUserId(userBeanId);
					tb_relation.setUsertypeId(Integer.parseInt(userTps));
					typeRelationBiz.insertSelective(tb_relation);
				}
			}
		} catch (Exception e) {
			log.error("[用户相关操作]-[添加角色类型]-异常，错误message:"+e.getMessage());
			throw new BaseException("[用户相关操作]-[添加角色类型]-异常，错误message:"+
					e.getMessage(),RestCodeConstants.THROW_ERROR_CODE);
		}
		log.info("[用户相关操作]-[添加角色类型] end 。");
		return objectRestResp.rel(true);
	}
	
}
